import { Injectable } from '@angular/core';
import { Observable, Observer } from 'rxjs';

import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';

/**
 * 确认框
 * 
 * ```ts 
    this.confirmModalSrc.info('<b>这是确认信息(粗体)</b>').subscribe(ok => {
        this.messageSrc.info('确认');
    });
 * ```
 *
 */
@Injectable({ providedIn: 'root' })
export class ConfirmService {
  constructor(private modalSrc: NzModalService) {}

  confirm(content: string): Observable<void> {
    return this.common('需要确认操作', content);
  }

  danger(content: string): Observable<void> {
    return this.common('需要确认操作', content, true);
  }

  private common(title: string, content: string, danger = false): Observable<void> {

		return new Observable((observer: Observer<void>) => {
			const modal: NzModalRef = this.modalSrc.confirm<boolean>({
				nzTitle: title,
				nzContent: content,
				nzOkDanger: danger,
				nzOnOk: () => modal.destroy(true),
				nzOnCancel: () => modal.destroy(false)
			});
			const afterClose$ = modal.afterClose.subscribe((res: boolean) => {
				if (res) {
					observer.next();
				}
				observer.complete();
				afterClose$.unsubscribe();
			});
		});
  }
}
